import java.util.*;

/**
 * @author LKQ
 * @date 2022/3/27 20:27
 * @description 双指针
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] nums = {10,1,2,4,7,2};
        System.out.println(solution.longestSubarray(nums, 5));
    }
    public int longestSubarray(int[] nums, int limit) {
        // 不能用TreeSet，虽然都能排序，但是treeSet移除左边元素，若存在相同的元素，那么无法准确移除左边的
        TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
        int n = nums.length;
        int left = 0, right = 0;
        int ret = 0;
        while (right < n) {
            map.put(nums[right], map.getOrDefault(nums[right], 0) + 1);
            while (map.lastKey() - map.firstKey() > limit) {
                map.put(nums[left], map.get(nums[left]) - 1);
                if (map.get(nums[left]) == 0) {
                    map.remove(nums[left]);
                }
                left++;
            }
            ret = Math.max(ret, right - left + 1);
            right++;
        }
        return ret;
    }
}
